package com.yyx.lgb.manager.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yyx.lgb.common.exception.LgbException;
import com.yyx.lgb.manager.mapper.SysRoleUserMapper;
import com.yyx.lgb.manager.mapper.SysUserMapper;
import com.yyx.lgb.manager.service.SysUserService;
import com.yyx.lgb.model.dto.system.AssginRoleDto;
import com.yyx.lgb.model.dto.system.LoginDto;
import com.yyx.lgb.model.dto.system.SysUserDto;
import com.yyx.lgb.model.entity.system.SysUser;
import com.yyx.lgb.model.vo.common.ResultCodeEnum;
import com.yyx.lgb.model.vo.system.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public LoginVo login(LoginDto loginDto) {

        String captcha = loginDto.getCaptcha();//输入的验证码
        String codeKey = loginDto.getCodeKey();//redis中验证码的数据key
        String redisCode = redisTemplate.opsForValue().get("user:validateCode" + codeKey);
        if(StrUtil.isEmpty(redisCode) || !StrUtil.equalsIgnoreCase(redisCode , captcha)) {
            throw new LgbException(ResultCodeEnum.VALIDATECODE_ERROR) ;
        }
        // 验证通过删除redis中的验证码
        redisTemplate.delete("user:validateCode" + codeKey) ;
        //1.提交用户名 loginDto取到
        String userName = loginDto.getUserName();

        //2.根据用户名查询数据库表 sys_user表
        SysUser sysUser = sysUserMapper.selectByUserName(userName);

        //3.根据用户名查对应的信息 用户不存在  返回错误信息
        if (sysUser == null){
            //throw new RuntimeException("用户名或密码错误");
            throw new LgbException(ResultCodeEnum.LOGIN_ERROR);
        }
        //4.用户存在
        //5.获取输入的密码，比较输入的密码和数据库的密码
        String inputPassword = loginDto.getPassword();  //输入的密码
        String password = sysUser.getPassword();  //数据库的密码
        //输入的密码加密
        String md5InputPassword = DigestUtils.md5DigestAsHex(inputPassword.getBytes());
        //比较  取反
        if (!md5InputPassword.equals(password)){
            //throw new RuntimeException("密码错误");
            throw new LgbException(ResultCodeEnum.LOGIN_ERROR);
        }
        //6.密码一致  登陆成功  生成唯一标识 token
        String token = UUID.randomUUID().toString().replace("-", "");

        //7.登录信息存储到redis中
        // key：token   value：用户信息
        redisTemplate.opsForValue()
                .set("user:login"+token, JSON.toJSONString(sysUser),30, TimeUnit.MINUTES);

        //8.返回LoginVo对象
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        return loginVo;
    }

    @Override
    public SysUser getUserinfo(String token) {
        String userJson = redisTemplate.opsForValue().get("user:login" + token);
        SysUser sysUser = JSON.parseObject(userJson, SysUser.class);
        return sysUser;
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete("user:login" + token);
    }

    @Override
    public PageInfo<SysUser> findByPage(SysUserDto sysUserDto, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
      List<SysUser>sysUserList= sysUserMapper.findByPage(sysUserDto);
      PageInfo pageInfo=new PageInfo(sysUserList);
        return pageInfo;
    }

    @Override
    public void saveSysUser(SysUser sysUser) {
        //根据输入的用户名查询用户
        SysUser sysUser1 = sysUserMapper.selectByUserName(sysUser.getUserName());
        if(sysUser1!=null){
            throw new LgbException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }
        //不存在 密码进行加密
        String password = sysUser.getPassword();
        String s = DigestUtils.md5DigestAsHex(password.getBytes());
        sysUser.setPassword(s);
        sysUser.setStatus(1);
        sysUserMapper.savaSysUser(sysUser);
    }

    @Override
    public void updateSysUser(SysUser sysUser) {
        sysUserMapper.updateSysUser(sysUser);

    }

    @Override
    public void deleteById(Long userId) {
        sysUserMapper.deleteById(userId);
    }
    @Override
    public void doAssign(AssginRoleDto assginRoleDto) {

        // 1.根据userId 删除用户之前分配角色数据
        sysRoleUserMapper.deleteByUserId(assginRoleDto.getUserId()) ;

        // 2.重新分配新的角色数据
        List<Long> roleIdList = assginRoleDto.getRoleIdList();
        //遍历得到每个角色id
        roleIdList.forEach(roleId->{
            sysRoleUserMapper.doAssign(assginRoleDto.getUserId(),roleId);
        });
    }
}
